import { app, BrowserWindow, ipcMain, shell, Menu } from 'electron';
import * as path from 'path';
import { setupIpcHandlers } from './ipc-handlers';
import { createServer } from '../server';

let mainWindow: BrowserWindow | null = null;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      webviewTag: true,  // 启用webview标签支持
      preload: path.join(__dirname, 'preload.js'),
    },
    titleBarStyle: 'hiddenInset',
  });

  const isDev = process.env.NODE_ENV === 'development';
  
  if (isDev) {
    mainWindow.loadURL('http://localhost:3000');
    mainWindow.webContents.openDevTools();
  } else {
    mainWindow.loadFile(path.join(__dirname, '../renderer/index.html'));
  }

  // 创建应用菜单，包含打印功能
  const template = [
    {
      label: '文件',
      submenu: [
        {
          label: '打印...',
          accelerator: 'CmdOrCtrl+P',
          click: () => {
            if (mainWindow && mainWindow.webContents) {
              // 打印当前页面
              mainWindow.webContents.print({
                silent: false,
                printBackground: true,
                color: true,
                margins: {
                  marginType: 'printableArea'
                },
                landscape: false,
                scaleFactor: 100
              }, (success, failureReason) => {
                if (!success) {
                  console.error('打印失败:', failureReason);
                }
              });
            }
          }
        },
        {
          label: '打印预览',
          accelerator: 'CmdOrCtrl+Shift+P',
          click: () => {
            if (mainWindow && mainWindow.webContents) {
              // 打开打印预览
              mainWindow.webContents.printToPDF({
                printBackground: true,
                color: true,
                margins: {
                  marginType: 'printableArea'
                },
                landscape: false,
                scaleFactor: 100
              }).then((data) => {
                // 可以保存PDF或显示预览
                console.log('PDF生成成功，大小:', data.length, 'bytes');
                // 这里可以添加保存PDF的逻辑
              }).catch((error) => {
                console.error('生成PDF失败:', error);
              });
            }
          }
        },
        { type: 'separator' },
        {
          label: '退出',
          accelerator: process.platform === 'darwin' ? 'Cmd+Q' : 'Ctrl+Q',
          click: () => {
            app.quit();
          }
        }
      ]
    },
    {
      label: '编辑',
      submenu: [
        { label: '撤销', accelerator: 'CmdOrCtrl+Z', role: 'undo' },
        { label: '重做', accelerator: 'Shift+CmdOrCtrl+Z', role: 'redo' },
        { type: 'separator' },
        { label: '剪切', accelerator: 'CmdOrCtrl+X', role: 'cut' },
        { label: '复制', accelerator: 'CmdOrCtrl+C', role: 'copy' },
        { label: '粘贴', accelerator: 'CmdOrCtrl+V', role: 'paste' },
        { label: '全选', accelerator: 'CmdOrCtrl+A', role: 'selectall' }
      ]
    },
    {
      label: '视图',
      submenu: [
        { label: '重新加载', accelerator: 'CmdOrCtrl+R', role: 'reload' },
        { label: '强制重新加载', accelerator: 'CmdOrCtrl+Shift+R', role: 'forceReload' },
        { label: '开发者工具', accelerator: 'F12', role: 'toggleDevTools' },
        { type: 'separator' },
        { label: '实际大小', accelerator: 'CmdOrCtrl+0', role: 'resetZoom' },
        { label: '放大', accelerator: 'CmdOrCtrl+Plus', role: 'zoomIn' },
        { label: '缩小', accelerator: 'CmdOrCtrl+-', role: 'zoomOut' },
        { type: 'separator' },
        { label: '全屏', accelerator: 'F11', role: 'togglefullscreen' }
      ]
    },
    {
      label: '帮助',
      submenu: [
        {
          label: '关于',
          click: () => {
            if (mainWindow) {
              mainWindow.webContents.executeJavaScript(`
                const { Modal } = require('antd');
                Modal.info({
                  title: '关于 Easy Share Web',
                  content: '多平台视频分发工具 v1.1.0\\n\\n支持抖音、哔哩哔哩、小红书等平台的视频一键发布。',
                  okText: '确定'
                });
              `).catch(() => {
                // 如果无法执行JavaScript，则在控制台显示信息
                console.log('Easy Share Web v1.1.0 - 多平台视频分发工具');
              });
            }
          }
        }
      ]
    }
  ];

  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);

  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

app.whenReady().then(() => {
  createWindow();
  setupIpcHandlers();
  createServer(); // 启动后端服务

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

// 安全设置
app.on('web-contents-created', (_, contents) => {
  contents.setWindowOpenHandler(({ url }) => {
    shell.openExternal(url);
    return { action: 'deny' };
  });
});
